CODE 50. Remove Duplicates from Sorted List II

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/09/29/2013-09-29-CODE 50 Remove Duplicates from Sorted List II/

访问原文「CODE 50. Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public ListNode deleteDuplicates(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
if (null == head) {
return null;
}
ListNode node = new ListNode(0);
ListNode next = head.next;
int currentVal = head.val;
ListNode currentNode = node;
boolean isDouble = false;
while (null != next) {
if (next.val > currentVal) {
if (!isDouble) {
currentNode.next = new ListNode(currentVal);
currentNode = currentNode.next;
}
isDouble = false;
currentVal = next.val;
} else if (next.val == currentVal) {
isDouble = true;
}
next = next.next;
}
if (!isDouble) {
currentNode.next = new ListNode(currentVal);
}
return node.next;
}
Jerky Lu wechat
欢迎加入微信公众号